package com.daigou.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.daigou.constants.CommonConstants;
import com.daigou.constants.URLConstants;
import com.daigou.model.Shop;
import com.daigou.model.User;
import com.daigou.service.ShopService;
import com.daigou.service.UserService;
import com.daigou.tools.Md5;

public class LoginInterceptor implements HandlerInterceptor {
	private static final Logger LOGGER = LoggerFactory.getLogger(LoginInterceptor.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ShopService shopService;
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object obj, Exception err)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object obj, ModelAndView mav)
			throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object obj) throws Exception {
		// 获取request的cookie
		Cookie[] cookies = request.getCookies();
		if (null == cookies) {
			LOGGER.info("没有cookie==============");
			// 没有找到登录状态则重定向到登录页，返回false，不执行原来controller的方法
			request.getRequestDispatcher(URLConstants.ADMIN_LOGIN_URL).forward(request, response);
			return false;
		} else {
			String userId = null;
			String userToken = null;
			//遍历cookie如果找到登录状态则返回true执行原来controller的方法
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(CommonConstants.USER_ID)) {
					userId = cookie.getValue();
					LOGGER.info("cookie(userId)=============="+userId);
					continue;
				}
				if (cookie.getName().equals(CommonConstants.USER_TOKEN)) {
					userToken = cookie.getValue();
					LOGGER.info("cookie(userToken)=============="+userToken);
					continue;
				}
			}
			if(userId == null || "".equals(userId) || userToken == null || "".equals(userToken)){
				request.getRequestDispatcher(URLConstants.ADMIN_LOGIN_URL).forward(request, response);
				LOGGER.info("userId和userToken都是null");
				return false;
			}else{
				long userIdLong = 0L;
				try{
					userIdLong = Long.parseLong(userId);
				}catch(Exception ex){
					ex.printStackTrace();
					LOGGER.info("userId传入异常："+userId);
					request.getRequestDispatcher(URLConstants.ADMIN_LOGIN_URL).forward(request, response);
					return false;
				}
				User user = userService.selectByPrimaryKey(userIdLong);
				if(user == null){
					LOGGER.info("通过userId未找到user"+userIdLong 	);
					request.getRequestDispatcher(URLConstants.ADMIN_LOGIN_URL).forward(request, response);
					return false;
				}
				String dbToken = Md5.MD5(user.getId()+"_"+user.getLoginName()+"_"+user.getPwd());
				if(userToken.equals(dbToken)){
					//状态,0,冻结，10，待完善user，11，待完善shop,20,ok
					LOGGER.info("user的status="+user.getStatus());
					//将user放入request缓存
					request.setAttribute(CommonConstants.USER_INFO, user);
					String requestUri = request.getRequestURI();
					if(user.getStatus() == 20){
						if(user.getShopId() == null){
							return false;
						}
						Shop shop = shopService.selectByPrimaryKey(user.getShopId());
						request.setAttribute(CommonConstants.SHOP_INFO, shop);
						if(requestUri.indexOf(URLConstants.DONE_USER_URL_TAG) >= 0 || requestUri.indexOf(URLConstants.DONE_SHOP_URL_TAG) >= 0){
							request.getRequestDispatcher(URLConstants.ADMIN_INDEX_URL).forward(request, response);
						}
						return true;
					}
					if(user.getStatus() == 0){
						request.getRequestDispatcher(URLConstants.ADMIN_LOGIN_URL).forward(request, response);
						return false;
					}
					if(requestUri.indexOf(URLConstants.UPLOAD_URL_TAG) >= 0){
						return true;
					}
					if(user.getStatus() == 10){
						if(requestUri.indexOf(URLConstants.DONE_USER_URL_TAG) >= 0){
							return true;
						}else{
							request.getRequestDispatcher(URLConstants.DONE_USER_URL).forward(request, response);
							return false;
						}
					}else if(user.getStatus() == 11){
						if(requestUri.indexOf(URLConstants.DONE_USER_URL_TAG) >= 0 || requestUri.indexOf(URLConstants.DONE_SHOP_URL_TAG) >= 0){
							return true;
						}else{
							request.getRequestDispatcher(URLConstants.DONE_SHOP_URL).forward(request, response);
							return false;
						}
					}else{
						return true;
					}
				}else{
					LOGGER.info("数据库中的token="+dbToken+",用户传入的userToken="+userToken);
					request.getRequestDispatcher(URLConstants.ADMIN_LOGIN_URL).forward(request, response);
					return false;
				}
			}
		}
	}
}
